package com.xp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xp.dto.flow.FlowExecutionDTO;
import com.xp.dto.flow.FlowQueryRequest;
import com.xp.dto.flow.FlowExecutionRequest;
import com.xp.entity.FlowExecution;
import com.xp.entity.FlowDefinition;
import com.xp.mapper.FlowDefinitionMapper;
import com.xp.mapper.FlowExecutionMapper;
import com.xp.service.FlowDefinitionService;
import com.xp.service.FlowExecutionService;
import com.xp.service.impl.BaseServiceImpl;
import com.xp.utils.Result;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.flow.LiteflowResponse;
import com.yomahub.liteflow.builder.el.LiteFlowChainELBuilder;
import com.yomahub.liteflow.slot.DefaultContext;
import com.xp.service.FlowDataConvertService;
import com.xp.dto.LiteFlowConvertResult;
import com.xp.dto.LogicFlowData;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 流程执行服务实现类
 *
 * @author xp
 * @since 2025-01-01
 */
@Service
@RequiredArgsConstructor
public class FlowExecutionServiceImpl extends BaseServiceImpl<FlowExecutionMapper, FlowExecution> implements FlowExecutionService {

    private static final Logger log = LoggerFactory.getLogger(FlowExecutionServiceImpl.class);

    private final FlowExecutionMapper flowExecutionMapper;
    private final FlowDefinitionMapper flowDefinitionMapper;
    private final FlowExecutor flowExecutor;
    private final FlowDefinitionService flowDefinitionService;
    private final FlowDataConvertService flowDataConvertService;
    private final ObjectMapper objectMapper;

    /**
     * 分页查询流程执行记录
     */
    @Override
    public Result<IPage<FlowExecutionDTO>> getFlowExecutionPage(Page<FlowExecutionDTO> page, FlowQueryRequest queryRequest) {
        try {
            // 创建FlowExecution类型的分页对象
            Page<FlowExecution> executionPage = new Page<>(page.getCurrent(), page.getSize());
            IPage<FlowExecution> resultPage = flowExecutionMapper.selectFlowExecutionPage(
                executionPage,
                queryRequest.getFlowCode(),
                queryRequest.getStatus(),
                queryRequest.getCreatorId(),
                queryRequest.getStartTimeBegin(),
                queryRequest.getStartTimeEnd()
            );

            // 转换为DTO
            IPage<FlowExecutionDTO> dtoPage = resultPage.convert(this::convertToDTO);
            return Result.success(dtoPage);
        } catch (Exception e) {
            log.error("分页查询流程执行记录失败", e);
            return Result.error("查询流程执行记录失败");
        }
    }

    /**
     * 同步执行流程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> executeFlowSync(String flowCode, Object inputData, Long executorId, String applicationName) {
        try {
            // 创建执行请求
            FlowExecutionRequest request = new FlowExecutionRequest();
            request.setFlowCode(flowCode);
            request.setInputData(inputData);
            request.setCreatorId(executorId);

            // 创建执行记录
            FlowExecution execution = createExecutionRecord(request);

            // 集成LiteFlow引擎执行流程
            log.info("开始同步执行流程，执行ID：{}，流程编码：{}", execution.getExecutionId(), execution.getFlowCode());

            // 更新状态为运行中
            execution.setStatus("RUNNING");
            execution.setStartTime(LocalDateTime.now());
            flowExecutionMapper.updateById(execution);

            // 执行LiteFlow流程
            Object result = executeLiteFlow(execution, inputData);

            // 更新执行结果
            execution.setStatus("SUCCESS");
            execution.setEndTime(LocalDateTime.now());
            execution.setDuration(System.currentTimeMillis() - execution.getStartTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
            execution.setOutputData(result != null ? result.toString() : null);
            flowExecutionMapper.updateById(execution);

            log.info("流程执行完成，执行ID：{}", execution.getExecutionId());

            return Result.success(execution.getExecutionId());
        } catch (Exception e) {
            log.error("同步执行流程失败", e);
            return Result.error("执行流程失败");
        }
    }

    /**
     * 异步执行流程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> executeFlowAsync(String flowCode, Object inputData, Long executorId, String applicationName) {
        try {
            // 创建执行请求
            FlowExecutionRequest request = new FlowExecutionRequest();
            request.setFlowCode(flowCode);
            request.setInputData(inputData);
            request.setCreatorId(executorId);

            // 创建执行记录
            FlowExecution execution = createExecutionRecord(request);

            // 异步执行流程
            CompletableFuture.runAsync(() -> {
                try {
                    log.info("开始异步执行流程，执行ID：{}，流程编码：{}", execution.getExecutionId(), execution.getFlowCode());

                    // 更新状态为运行中
                    execution.setStatus("RUNNING");
                    execution.setStartTime(LocalDateTime.now());
                    flowExecutionMapper.updateById(execution);

                    // 执行LiteFlow流程
                    Object result = executeLiteFlow(execution, inputData);

                    // 更新执行结果
                    execution.setStatus("SUCCESS");
                    execution.setEndTime(LocalDateTime.now());
                    execution.setDuration(System.currentTimeMillis() - execution.getStartTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
                    execution.setOutputData(result != null ? result.toString() : null);
                    flowExecutionMapper.updateById(execution);

                    log.info("异步流程执行完成，执行ID：{}", execution.getExecutionId());
                } catch (Exception e) {
                    log.error("异步执行流程失败，执行ID：{}", execution.getExecutionId(), e);

                    // 更新状态为失败
                    execution.setStatus("FAILED");
                    execution.setEndTime(LocalDateTime.now());
                    execution.setErrorMessage(e.getMessage());
                    flowExecutionMapper.updateById(execution);
                }
            });

            return Result.success(execution.getExecutionId());
        } catch (Exception e) {
            log.error("异步执行流程失败", e);
            return Result.error("执行流程失败");
        }
    }

    /**
     * 停止流程执行
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> stopFlowExecution(Long executionId) {
        try {
            if (executionId == null) {
                return Result.error("执行ID不能为空");
            }

            FlowExecution execution = flowExecutionMapper.selectById(executionId);
            if (execution == null) {
                return Result.error("流程执行记录不存在");
            }

            if (!"RUNNING".equals(execution.getStatus()) && !"PENDING".equals(execution.getStatus())) {
                return Result.error("只能停止运行中或待执行的流程");
            }

            // TODO: 调用LiteFlow引擎停止流程执行

            // 更新执行状态
            execution.setStatus("STOPPED"); // 已停止
            execution.setEndTime(LocalDateTime.now());
            execution.setErrorMessage("用户手动停止");

            if (execution.getStartTime() != null) {
                long duration = java.time.Duration.between(execution.getStartTime(), execution.getEndTime()).toMillis();
                execution.setDuration(duration);
            }

            int result = flowExecutionMapper.updateById(execution);
            if (result > 0) {
                log.info("停止流程执行成功，执行ID：{}", executionId);
                return Result.success("停止流程执行成功");
            } else {
                return Result.error("停止流程执行失败");
            }
        } catch (Exception e) {
            log.error("停止流程执行失败", e);
            return Result.error("停止流程执行失败");
        }
    }

    /**
     * 重新执行流程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<FlowExecutionDTO> reExecuteFlow(String executionId) {
        try {
            if (!StringUtils.hasText(executionId)) {
                return Result.error("执行ID不能为空");
            }

            FlowExecution originalExecution = flowExecutionMapper.selectByExecutionId(executionId);
            if (originalExecution == null) {
                return Result.error("原始流程执行记录不存在");
            }

            // 同步重新执行
            Result<Object> executeResult = executeFlowSync(
                originalExecution.getFlowCode(),
                originalExecution.getInputData(),
                originalExecution.getCreatorId(),
                "default" // 默认应用名称，因为原始记录可能没有这个字段
            );

            if (executeResult.getCode() == 200) {
                // 如果执行成功，返回新的执行记录DTO
                // 这里简化处理，实际应该根据executeResult.getData()中的执行ID查询新记录
                FlowExecutionDTO dto = convertToDTO(originalExecution);
                return Result.success(dto);
            } else {
                return Result.error(executeResult.getMessage());
            }
        } catch (Exception e) {
            log.error("重新执行流程失败", e);
            return Result.error("重新执行流程失败");
        }
    }

    /**
     * 根据执行ID获取流程执行记录
     */
    @Override
    public Result<FlowExecutionDTO> getFlowExecutionById(Long executionId) {
        try {
            if (executionId == null) {
                return Result.error("执行ID不能为空");
            }

            FlowExecution execution = flowExecutionMapper.selectById(executionId);
            if (execution == null) {
                return Result.error("流程执行记录不存在");
            }

            FlowExecutionDTO dto = convertToDTO(execution);
            return Result.success(dto);
        } catch (Exception e) {
            log.error("获取流程执行记录失败", e);
            return Result.error("获取流程执行记录失败");
        }
    }

    /**
     * 根据链路追踪ID获取流程执行记录
     */
    @Override
    public Result<FlowExecutionDTO> getFlowExecutionByTraceId(String traceId) {
        try {
            if (!StringUtils.hasText(traceId)) {
                return Result.error("链路追踪ID不能为空");
            }

            FlowExecution execution = flowExecutionMapper.selectByTraceId(traceId);
            if (execution == null) {
                return Result.error("流程执行记录不存在");
            }

            FlowExecutionDTO dto = convertToDTO(execution);
            return Result.success(dto);
        } catch (Exception e) {
            log.error("根据链路追踪ID获取流程执行记录失败", e);
            return Result.error("获取流程执行记录失败");
        }
    }

    /**
     * 根据流程编码获取执行记录列表
     */
    @Override
    public Result<List<FlowExecutionDTO>> getFlowExecutionsByFlowCode(String flowCode, Integer limit) {
        try {
            if (!StringUtils.hasText(flowCode)) {
                return Result.error("流程编码不能为空");
            }

            List<FlowExecution> executions = flowExecutionMapper.selectByFlowCode(flowCode);
            List<FlowExecutionDTO> dtoList = executions.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
            return Result.success(dtoList);
        } catch (Exception e) {
            log.error("根据流程编码获取执行记录失败", e);
            return Result.error("获取执行记录失败");
        }
    }

    /**
     * 获取运行中的流程执行记录
     */
    @Override
    public Result<List<FlowExecutionDTO>> getRunningFlowExecutions() {
        try {
            List<FlowExecution> executions = flowExecutionMapper.selectRunningExecutions();
            List<FlowExecutionDTO> dtoList = executions.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
            return Result.success(dtoList);
        } catch (Exception e) {
            log.error("获取运行中的流程执行记录失败", e);
            return Result.error("获取运行中的流程执行记录失败");
        }
    }

    /**
     * 获取失败的流程执行记录
     */
    @Override
    public Result<List<FlowExecutionDTO>> getFailedFlowExecutions(Integer limit) {
        try {
            List<FlowExecution> executions = flowExecutionMapper.selectFailedExecutions();
            List<FlowExecutionDTO> dtoList = executions.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
            return Result.success(dtoList);
        } catch (Exception e) {
            log.error("获取失败的流程执行记录失败", e);
            return Result.error("获取失败的流程执行记录失败");
        }
    }

    /**
     * 创建执行记录
     */
    private FlowExecution createExecutionRecord(FlowExecutionRequest request) {
        FlowExecution execution = new FlowExecution();
        BeanUtils.copyProperties(request, execution);

        // 生成执行ID
        execution.setExecutionId(generateExecutionId());

        // 设置初始状态
        execution.setStatus("PENDING"); // 待执行
        execution.setCreateTime(LocalDateTime.now());

        // 保存执行记录
        flowExecutionMapper.insert(execution);

        return execution;
    }

    /**
     * 生成执行ID
     */
    private String generateExecutionId() {
        return "EXEC_" + System.currentTimeMillis() + "_" + (int)(Math.random() * 1000);
    }

    /**
     * 转换实体为DTO
     */
    private FlowExecutionDTO convertToDTO(FlowExecution execution) {
        FlowExecutionDTO dto = new FlowExecutionDTO();
        BeanUtils.copyProperties(execution, dto);
        return dto;
    }

    /**
     * 重试流程执行
     *
     * @param executionId 流程执行记录ID
     * @return 重试结果
     */
    @Override
    public Result<String> retryFlowExecution(Long executionId) {
        try {
            if (executionId == null) {
                return Result.error("执行ID不能为空");
            }

            // 根据ID查询流程执行记录
            FlowExecution execution = flowExecutionMapper.selectById(executionId);
            if (execution == null) {
                return Result.error("流程执行记录不存在");
            }

            // 检查状态是否允许重试（只有失败的记录才能重试）
            if (!"FAILED".equals(execution.getStatus())) {
                return Result.error("只有失败的流程才能重试");
            }

            // 创建重试请求
            FlowExecutionRequest retryRequest = new FlowExecutionRequest();
            retryRequest.setFlowCode(execution.getFlowCode());
            retryRequest.setInputData(execution.getInputData());

            // 执行重试
            Result<Object> retryResult = executeFlowSync(
                execution.getFlowCode(),
                execution.getInputData(),
                execution.getCreatorId(),
                "default" // 默认应用名称，因为FlowExecution实体没有applicationName字段
            );
            if (retryResult.getCode() == 200) {
                return Result.success("重试成功，新执行ID：" + retryResult.getData());
            } else {
                return Result.error("重试失败：" + retryResult.getMessage());
            }
        } catch (Exception e) {
            log.error("重试流程执行失败", e);
            return Result.error("重试流程执行失败");
        }
    }

    /**
     * 获取流程输入数据
     * @param id 流程执行ID
     * @return 输入数据
     */
    @Override
    public Result<Object> getFlowInputData(Long id) {
        try {
            // 根据ID查询流程执行记录
            FlowExecution execution = flowExecutionMapper.selectById(id);
            if (execution == null) {
                return Result.error("流程执行记录不存在");
            }

            // 返回输入数据
            return Result.success(execution.getInputData());
        } catch (Exception e) {
            log.error("获取流程输入数据失败: {}", e.getMessage(), e);
            return Result.error("获取流程输入数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取流程输出数据
     * @param id 流程执行ID
     * @return 输出数据
     */
    @Override
    public Result<Object> getFlowOutputData(Long id) {
        try {
            // 根据ID查询流程执行记录
            FlowExecution execution = flowExecutionMapper.selectById(id);
            if (execution == null) {
                return Result.error("流程执行记录不存在");
            }

            // 返回输出数据
            return Result.success(execution.getOutputData());
        } catch (Exception e) {
            log.error("获取流程输出数据失败: {}", e.getMessage(), e);
            return Result.error("获取流程输出数据失败: " + e.getMessage());
        }
    }



    @Override
    public Result<Object> exportFlowExecutions(String flowCode, String startTime, String endTime, String format) {
        // TODO: 实现导出流程执行记录逻辑
        return Result.error("功能暂未实现");
    }

    /**
     * 执行LiteFlow流程
     */
    private Object executeLiteFlow(FlowExecution execution, Object inputData) {
        try {
            // 获取流程定义
             FlowDefinition flowDefinition = flowDefinitionMapper.selectByFlowCode(execution.getFlowCode());
             if (flowDefinition == null) {
                 throw new RuntimeException("流程定义不存在: " + execution.getFlowCode());
             }

             // 检查流程状态
             if (flowDefinition.getStatus() == null || flowDefinition.getStatus() != 1) {
                 throw new RuntimeException("流程未发布，无法执行: " + execution.getFlowCode());
             }

             // 检查LiteFlow配置
             if (!StringUtils.hasText(flowDefinition.getLiteflowConfig())) {
                 throw new RuntimeException("流程LiteFlow配置为空，请先转换流程: " + execution.getFlowCode());
             }

             // 手动构建流程（如果流程不存在则创建，如果存在则更新）
             buildLiteFlowChain(flowDefinition);

             // 准备节点配置数据，将解析后的配置作为inputData传递
             Map<String, Object> processedInputData = prepareNodeConfigurations(flowDefinition, inputData);

             // 使用FlowExecutor执行流程，将处理后的数据作为请求数据传递
             LiteflowResponse response = flowExecutor.execute2Resp(execution.getFlowCode(), processedInputData, DefaultContext.class);

             if (response.isSuccess()) {
                 return response.getSlot().getResponseData();
             } else {
                 throw new RuntimeException("流程执行失败: " + response.getMessage());
             }
        } catch (Exception e) {
            log.error("执行LiteFlow流程失败，执行ID：{}", execution.getExecutionId(), e);

            // 更新执行状态为失败
            execution.setStatus("FAILED");
            execution.setEndTime(LocalDateTime.now());
            execution.setErrorMessage(e.getMessage());
            if (execution.getStartTime() != null) {
                execution.setDuration(System.currentTimeMillis() - execution.getStartTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
            }
            flowExecutionMapper.updateById(execution);

            throw new RuntimeException("流程执行失败: " + e.getMessage(), e);
        }
    }

    /**
     * 手动构建LiteFlow流程
     * @param flowDefinition 流程定义
     */
    /**
     * 构建LiteFlow流程
     * 使用tag语法，同一类型的组件可以通过tag区分不同的实例
     */
    private void buildLiteFlowChain(FlowDefinition flowDefinition) {
        try {
            // 使用LiteFlowChainELBuilder构建流程
            // 如果流程不存在则创建，如果存在则更新
            LiteFlowChainELBuilder.createChain()
                    .setChainName(flowDefinition.getFlowCode())
                    .setEL(flowDefinition.getLiteflowConfig())
                    .build();

            log.info("成功构建LiteFlow流程: {}", flowDefinition.getFlowCode());
        } catch (Exception e) {
            log.error("构建LiteFlow流程失败: {}, 错误信息: {}", flowDefinition.getFlowCode(), e.getMessage(), e);
            throw new RuntimeException("构建LiteFlow流程失败: " + e.getMessage());
        }
    }

    /**
     * 准备节点配置数据
     * 将节点配置设置到上下文中，供组件使用
     */
    private Map<String, Object> prepareNodeConfigurations(FlowDefinition flowDefinition, Object inputData) {
        try {
            Map<String, Object> contextData = new HashMap<>();

            // 设置输入数据
            if (inputData != null) {
                if (inputData instanceof Map) {
                    contextData.putAll((Map<String, Object>) inputData);
                } else {
                    contextData.put("inputData", inputData);
                }
            }

            // 解析流程数据，获取节点配置
            if (StringUtils.hasText(flowDefinition.getFlowData())) {
                LogicFlowData logicFlowData = objectMapper.readValue(flowDefinition.getFlowData(), LogicFlowData.class);

                // 获取节点组件映射
                LiteFlowConvertResult convertResult = flowDataConvertService.convertToLiteFlow(logicFlowData);
                if (convertResult.isSuccess() && convertResult.getNodeComponentMapping() != null) {

                    // 为每个节点设置配置数据
                    for (Map.Entry<String, LiteFlowConvertResult.NodeComponentInfo> entry :
                         convertResult.getNodeComponentMapping().entrySet()) {

                        String nodeId = entry.getKey();
                        LiteFlowConvertResult.NodeComponentInfo nodeInfo = entry.getValue();

                        // 设置节点配置到上下文中
                        if (nodeInfo.getNodeConfig() != null) {
                            // 使用节点ID的前8位作为tag值（与getComponentName方法保持一致）
                            String tagValue = nodeId.replaceAll("-", "").substring(0, Math.min(8, nodeId.replaceAll("-", "").length()));

                            // 为每个配置项设置到上下文中，使用tag值作为前缀
                            for (Map.Entry<String, Object> configEntry : nodeInfo.getNodeConfig().entrySet()) {
                                String configKey = tagValue + "_" + configEntry.getKey();
                                contextData.put(configKey, configEntry.getValue());
                            }

                            log.debug("设置节点配置，节点ID: {}, tag: {}, 配置: {}", nodeId, tagValue, nodeInfo.getNodeConfig());
                        }
                    }
                }
            }

            return contextData;

        } catch (Exception e) {
            log.error("准备节点配置数据失败", e);
            // 如果配置准备失败，至少返回输入数据
            Map<String, Object> fallbackData = new HashMap<>();
            if (inputData != null) {
                if (inputData instanceof Map) {
                    fallbackData.putAll((Map<String, Object>) inputData);
                } else {
                    fallbackData.put("inputData", inputData);
                }
            }
            return fallbackData;
        }
    }

    @Override
    public Result<List<Object>> getFlowExecutionLogs(Long executionId) {
        // TODO: 实现获取流程执行日志逻辑
        return Result.error("功能暂未实现");
    }

    @Override
    public Result<List<Object>> getNodeExecutionDetails(Long executionId) {
        // TODO: 实现获取节点执行详情逻辑
        return Result.error("功能暂未实现");
    }

    @Override
    public Result<Object> pauseFlowExecution(Long executionId) {
        // TODO: 实现暂停流程执行逻辑
        return Result.error("功能暂未实现");
    }

    @Override
    public Result<Object> resumeFlowExecution(Long executionId) {
        // TODO: 实现恢复流程执行逻辑
        return Result.error("功能暂未实现");
    }

    @Override
    public Result<Object> getFlowExecutionStatus(Long executionId) {
        // TODO: 实现获取流程执行状态逻辑
        return Result.error("功能暂未实现");
    }

    @Override
    public Result<Object> batchStopFlowExecutions(List<Long> executionIds) {
        // TODO: 实现批量停止流程执行逻辑
        return Result.error("功能暂未实现");
    }

    @Override
    public Result<Map<String, Object>> getFlowExecutionData(String executionId) {
        // TODO: 实现获取流程执行输入输出数据逻辑
        return Result.error("功能暂未实现");
    }

    @Override
    public Result<List<Object>> getFlowExecutionNodes(String executionId) {
        // TODO: 实现获取流程执行节点逻辑
        return Result.error("功能暂未实现");
    }

    @Override
    public Result<Object> getFlowPerformanceAnalysis(String flowCode, Integer days) {
        // TODO: 实现获取流程性能分析逻辑
        return Result.error("功能暂未实现");
    }

    @Override
    public Result<Object> cleanupExpiredRecords(Integer retentionDays) {
        // TODO: 实现清理过期执行记录逻辑
        return Result.error("功能暂未实现");
    }

    @Override
    public Result<Object> getFlowExecutionStatistics(Integer days) {
        // TODO: 实现获取流程执行统计信息逻辑
        return Result.error("功能暂未实现");
    }

    @Override
    public Result<Object> getFlowExecutionTrends(Integer days, String granularity) {
        // TODO: 实现获取流程执行趋势逻辑
        return Result.error("功能暂未实现");
    }

    /**
     * 获取流程执行趋势数据
     */
    @Override
    public Result<List<Map<String, Object>>> getFlowExecutionTrend(String flowCode, Integer days) {
        // TODO: 实现获取流程执行趋势逻辑
        return Result.error("功能暂未实现");
    }

    /**
     * 获取流程执行性能分析
     */
    @Override
    public Result<Map<String, Object>> getFlowExecutionPerformance(String flowCode) {
        // TODO: 实现获取流程执行性能分析逻辑
        return Result.error("功能暂未实现");
    }

    /**
     * 清理过期的执行记录
     *
     * @param days 保留天数
     * @return 清理结果
     */
    @Override
    public Result<Object> cleanExpiredExecutions(Integer days) {
        try {
            if (days == null || days <= 0) {
                return Result.error("保留天数必须大于0");
            }

            // TODO: 实现清理过期执行记录逻辑
            // LocalDateTime expireTime = LocalDateTime.now().minusDays(days);
            // int deletedCount = flowExecutionMapper.deleteExpiredExecutions(expireTime);

            return Result.success("清理功能暂未实现");
        } catch (Exception e) {
            log.error("清理过期执行记录失败", e);
            return Result.error("清理过期执行记录失败");
        }
    }
}
